﻿// Decompiled with JetBrains decompiler
// Type: Commom.Util.ThreadUtil
// Assembly: MT5Trade, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 8045A2CB-DBD6-41AD-8804-F98CAC1BDC8D
// Assembly location: C:\projects\trade\trade_tool\trade0812\MT5Trade.dll

using System;
using System.Collections.Generic;
using System.Threading.Tasks;

#nullable enable
namespace Commom.Util;

public static class ThreadUtil
{
  public static void WaitAll(params Action[] actions)
  {
    if (actions == null)
      return;
    List<Task> taskList = new List<Task>();
    foreach (Action action in actions)
      taskList.Add(Task.Factory.StartNew(action, TaskCreationOptions.None));
    Task.WaitAll(taskList.ToArray());
  }

  public static void ParallelExecute(params Action[] actions) => Parallel.Invoke(actions);

  public static void ParallelExecute(Action action, int count = 1, ParallelOptions options = null)
  {
    if (options == null)
      Parallel.For(0, count, (Action<int>) (i => action()));
    else
      Parallel.For(0, count, options, (Action<int>) (i => action()));
  }

  public static void ManyTask<T>(int everyThread, IList<T> datas, Action<T> func)
  {
    if (datas == null)
      return;
    int num = 0;
    List<Task> taskList = new List<Task>();
    int count = datas.Count;
    foreach (T data in (IEnumerable<T>) datas)
    {
      ++num;
      if (taskList.Count > everyThread || num == count)
      {
        foreach (Task task in taskList)
          task.Start();
        Task.WaitAll(taskList.ToArray());
        taskList.Clear();
      }
      Task task1 = new Task((Action<object>) (p => func((T) p)), (object) data);
      if (num == count)
        task1.Start();
      else
        taskList.Add(task1);
    }
  }
}
